const { execSync } = require('child_process');
const path = require('path');

console.log('🚀 开始打包桌面应用...');

// 设置环境变量
process.env.ELECTRON_MIRROR = 'https://npmmirror.com/mirrors/electron/';
process.env.ELECTRON_BUILDER_BINARIES_MIRROR = 'https://npmmirror.com/mirrors/electron-builder-binaries/';

try {
  // 1. 构建前端
  console.log('📦 构建前端...');
  execSync('npm run build', { stdio: 'inherit' });
  
  // 2. 检查是否安装了electron-builder
  try {
    require('electron-builder');
    console.log('✅ electron-builder 已安装');
  } catch (error) {
    console.log('📥 安装 electron-builder...');
    execSync('npm install electron-builder --save-dev', { stdio: 'inherit' });
  }
  
  // 3. 清理之前的缓存
  console.log('🧹 清理缓存...');
  try {
    execSync('npx electron-builder install-app-deps', { stdio: 'inherit' });
  } catch (error) {
    console.log('⚠️ 清理缓存失败，继续打包...');
  }
  
  // 4. 打包应用
  console.log('🔨 打包桌面应用...');
  console.log('📡 使用镜像源:', process.env.ELECTRON_MIRROR);
  execSync('npx electron-builder', { stdio: 'inherit' });
  
  console.log('✅ 打包完成！应用文件在 release 目录中');
  
} catch (error) {
  console.error('❌ 打包失败:', error.message);
  console.log('💡 如果网络问题，请尝试：');
  console.log('   1. 检查网络连接');
  console.log('   2. 使用VPN或代理');
  console.log('   3. 手动下载Electron二进制文件');
  process.exit(1);
} 